from rest_framework.renderers import JSONRenderer


def res_message(status=True, message="success", data=""):
    """
    格式化响应体

    :param bool status: 响应状态 True成功、False失败
    :param str message: 响应描述
    :param str dict data: 响应内容
    :return: dict
    """
    assert isinstance(status, bool)
    assert isinstance(message, (int, str))
    assert isinstance(data, (str, dict, list))

    res = {
        "status": status,
        "msg": message,
        "data": data
    }

    return res


# 导入控制返回的JSON格式的类
class CustomRenderer(JSONRenderer):
    # 重构render方法
    def render(self, data, accepted_media_type=None, renderer_context=None):
        if not renderer_context:
            return super().render(data, accepted_media_type, renderer_context)

        # 判断实例的类型，返回的数据可能是列表也可能是字典
        if isinstance(data, dict):
            # 如果是字典的话应该是返回的数据，会包含msg, code, status等字段必须抽离出来
            if 'detail' in data.keys():
                msg = data.pop('msg', 'error')
                status = data.pop('status', False)
            else:
                msg = data.pop('msg', 'success')
                status = data.pop('status', True)
            # 自定义返回数据格式
            ret = res_message(status, msg, data)
        else:
            ret = data
        # 返回JSON数据
        return super().render(ret, accepted_media_type, renderer_context)
